package es.usc.citius.servando.calendula.settings;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import es.usc.citius.servando.calendula.CalendulaActivity;
import es.usc.citius.servando.calendula.mvp.IPresenter;
import es.usc.citius.servando.calendula.mvp.IView;
import es.usc.citius.servando.calendula.util.PreferenceUtils;

public abstract class CalendulaPrefsFragment<V extends IView, P extends IPresenter<V>>
        extends PreferenceFragmentCompat implements IView, SharedPreferences.OnSharedPreferenceChangeListener {

    public abstract P getPresenter();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getPresenter().attachView((V) this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroy() {
        getPresenter().detachView();
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        PreferenceUtils.instance().preferences().registerOnSharedPreferenceChangeListener(this);
        ((CalendulaActivity)getActivity()).getSupportActionBar().setTitle(getFragmentTitle());
        getPresenter().start();
    }

    @Override
    public void onPause() {
        super.onPause();
        PreferenceUtils.instance().preferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    /**
     * A [StringRes] resource that will be used to set the actionbar's title when navigating to this fragment
     */
    public abstract int getFragmentTitle();
}
